﻿using Agile.Infra.Core.Agile.Extensions;
using Microsoft.Extensions.Logging;
using System.Text;

namespace Agile.Infra.WeiXin;

public partial class AppletService
{
    public async Task<string> GetUserPhoneNumberAsync(string code, string openID)
    {
        try
        {
            var accessToken = await GetAccessTokenAsync();

            var requestData = new
            {
                code = code,
                openid = openID
            };

            using (var content = new StringContent(requestData.ToJsonString(), Encoding.UTF8, "application/json"))
            {
                var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, $"{_appleOptions.ServerUrl}/wxa/business/getuserphonenumber?access_token={accessToken}");
                httpRequestMessage.Content = content;
                var response = await HttpRequestAsync(openID, httpRequestMessage);
                var result = response.ToJsonObject<PhoneNumberModel>();
                if (result.errcode == 0)
                {
                    return result.phone_info.purePhoneNumber;
                }
                return string.Empty;
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "小程序获取AccessToken异常");
        }
        return string.Empty;
    }

    #region 响应实体

    internal class PhoneNumberModel
    {
        /// <summary> 错误码 </summary>
        public int errcode { get; set; }

        /// <summary> 错误信息 </summary>
        public string errmsg { get; set; }

        /// <summary> 用户手机号信息 </summary>
        public PhoneModel phone_info { get; set; }
    }

    internal class PhoneModel
    {
        /// <summary> 用户绑定的手机号（国外手机号会有区号） </summary>
        public string phoneNumber { get; set; }

        /// <summary> 没有区号的手机号 </summary>
        public string purePhoneNumber { get; set; }

        /// <summary> 区号 </summary>
        public string countryCode { get; set; }
    }

    #endregion
}
